package com.masteringwave.views;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import javax.cache.Cache;
import javax.cache.CacheException;
import javax.cache.CacheManager;

import com.google.wave.api.*;

@SuppressWarnings("serial")
public class EmbedUrlRobotServlet extends AbstractRobotServlet {
	public final String URLFIELD = "URL_FIELD";
	Cache cache;
	public EmbedUrlRobotServlet(){
		super();

        try {
            cache = CacheManager.getInstance().getCacheFactory().createCache(Collections.emptyMap());
        } catch (CacheException e) {
            //
        }

	}
	
	@Override
	public void processEvents(RobotMessageBundle bundle) {
		Wavelet wavelet = bundle.getWavelet();
		String creator = wavelet.getCreator();
		if (bundle.wasSelfAdded()) {

			Blip blip = wavelet.appendBlip();
			TextView textView = blip.getDocument();
			textView.appendMarkup("<p><b>Inline the url</b></p>\n");
			FormView form = textView.getFormView();
			form.append(new FormElement(ElementType.INPUT, URLFIELD,"http://"));
			form.append(new FormElement(ElementType.BUTTON, "submit", "INSERT"));
			
		}

		for (Event e : bundle.getEvents()) {

			if (e.getType() == EventType.FORM_BUTTON_CLICKED) {
				
				Blip blip = e.getBlip();
				FormView form = blip.getDocument().getFormView();
				FormElement urlElement = form.getFormElement(URLFIELD);
				
				GadgetView gadgetView= blip.getDocument().getGadgetView();
				gadgetView.append(new Gadget("http://pollenvarsel.appspot.com/gadget?url="+urlElement.getValue()));
				
			}

		}

	}


}